function pi = solve_pi_xx(P,params)

% OBJECTIVE : Given guess of price index, calculate pi

  function pi = calc_pi(x_x,params)
    % Calculate aggregate global profits, given x_x              
    s = params.sigma;
    Cx = params.Cx;
    mu = params.mu;
    K = params.K;
        
    exporters = repmat(params.potential_entrants,1,K).*x_x.^(-params.gamma);      % (KxK)    
    tmp = sum(sum(exporters.*Cx));    
    pi = (mu/s - tmp/sum(params.L))/(1-mu/s);    
  end

  function ret = solve_pi_xx2(pi,P,params)
    Y = params.L*(1+pi);
    x_x = cutoff_imo_x(P,Y,params);
    pi2 = calc_pi(x_x,params);
    ret = pi2 - pi;
  end


pistart = .1;
func = @(pi) solve_pi_xx2(pi,P,params);
options = optimset('Display','none','MaxIter',1000,'MaxFunEvals',20000,'TolFun',1e-8,'TolX',1e-8);
[pi,fval,exitflag,output] = fsolve(func,pistart,options);

if (pi<0) 
    pi=0;
end

end